<template>
  <div class="view-fill">
    <div
      v-if="!modifyInfo.visible && !assetDetailInfo.visible"
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        title="资产转移详情"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        :needReturn="!$route.query.processInstanceId"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button
            v-if="$permission('detail:excel') && infoList.data.status !== 1"
            @click="exportExcel"
            >导出excel</el-button
          >
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button v-if="canApprove" @click="btnFlow('approve')"
            >批准</el-button
          >
          <el-button v-if="canReject" @click="btnFlow('reject')"
            >驳回</el-button
          >
          <el-button v-if="canRefuse" @click="btnFlow('refuse')"
            >拒绝</el-button
          >
          <el-button v-if="canRecall" @click="recall">撤回</el-button>
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <el-button v-if="canSalesReview" @click="salesReview">销审</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList" />
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :check-box="false"
                :tab-index="true"
                :field-list="tableInfo.fieldList"
                :isDynamic="true"
              >
                <template v-slot:col-assetName="scope">
                  <span class="slip-edit" @click="showAssetDetail(scope.row)">{{
                    scope.row.assetName
                  }}</span>
                </template>
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 修改 -->
    <asset-transfer-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :order-id="modifyInfo.orderId"
    />
    <!-- 资产明细 -->
    <asset-card-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      :title="assetDetailInfo.title"
    />
  </div>
</template>

<script setup>
import {
  getAssetTransfer,
  getAssetTransferDetailCustomizeListAll,
  submitAssetTransfer,
  refreshAssetTransfer,
  rejectAssetTransfer,
  refuseAssetTransfer,
  salesReviewTransfer,
  doReturnAssetTransfer,
  doCancelAssetTransfer,
  revokeAssetTransfer,
  checkAssetTransfer,
  reviewAssetTransfer,
  adjustmentAssetTransfer,
  printAssetTransferOrder,
  excelAssetTransferOrder,
} from '@/api/asset.js'
import { getCustomizeSetting } from '@/api/customize'
import { orderOpAffairAll } from '@/api/affair'
import { fatchTemplateByCode } from '@/api/base'
import AssetTransferModify from './modify'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const AssetCardDetail = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetCard/details')
)

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'tableRow', 'id'])

const infoList = ref({
  data: {},
  fieldList: [
    { label: '单号', value: 'orderNo', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '申请人', value: 'applyUserName', type: 'text' },
    { label: '申请时间', value: 'applyTime', type: 'text' },
    { label: '审核人', value: 'checkUserName', type: 'text' },
    { label: '审核时间', value: 'checkTime', type: 'text' },
    { label: '调整人', value: 'adjustUserName', type: 'text' },
    { label: '调整时间', value: 'adjustTime', type: 'text' },
    { label: '备注', value: 'remark', type: 'popover' },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id || props.tableRow.id,
      },
    },
    queryParams: {},
  },
})
const modifyInfo = ref({
  visible: false,
  orderId: '',
  title: '',
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [],
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
  title: '资产详情',
})
const affairTableInfo = ref({
  api: orderOpAffairAll,
  query: {
    //数字字典单据类型 资产转移：45
    orderType: 45,
    orderId: props.id || props.tableRow.id,
    sort: 'operate_time desc',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
//状态: 待提交:1,待审核:2,审批中:3,待调整:4,已完成:5,已中止：6,已驳回：7,已拒绝：8
//提交
const canSubmit = computed(() => {
  return (
    proxy.$permission('assetTransfer:submit') &&
    (infoList.value.data.status === 1 || infoList.value.data.status === 7)
  )
})
//批准
const canApprove = computed(() => {
  return (
    proxy.$permission('assetTransfer:approve') &&
    proxy.$store.state.permission.systemConfig.allow_assets_transfer_approval ==
      1 &&
    infoList.value.data.status === 2
  )
})
//驳回
const canReject = computed(() => {
  return (
    proxy.$permission('assetTransfer:reject') &&
    proxy.$store.state.permission.systemConfig.allow_assets_transfer_approval ==
      1 &&
    infoList.value.data.status === 2
  )
})
//拒绝
const canRefuse = computed(() => {
  return (
    proxy.$permission('assetTransfer:refuse') &&
    proxy.$store.state.permission.systemConfig.allow_assets_transfer_approval ==
      1 &&
    infoList.value.data.status === 2
  )
})
//撤回
const canRecall = computed(() => {
  return (
    proxy.$permission('assetTransfer:recall') &&
    (infoList.value.data.status === 2 ||
      (infoList.value.data.status === 5 &&
        proxy.$store.state.permission.systemConfig
          .allow_assets_transfer_approval == 0))
  )
})
//修改
const canUpdate = computed(() => {
  return (
    proxy.$permission('assetTransfer:update') &&
    (infoList.value.data.status === 1 || infoList.value.data.status === 7)
  )
})
// 销审
const canSalesReview = computed(() => {
  return (
    proxy.$permission('assetTransfer:salesReview') &&
    infoList.value.data.status === 5 &&
    proxy.$store.state.permission.systemConfig.allow_assets_transfer_approval !=
      0
  )
})
const canPrint = computed(() => {
  return proxy.$permission('detail:print') && infoList.value.data.status !== 1
})

watch(
  () => props.visible,
  (value) => {
    showDialog.value = value
  },
  {
    immediate: true,
  }
)
watch(
  () => modifyInfo.value.visible,
  (value) => {
    if (!value) {
      getMain()
      getList()
    }
  }
)

setData()
function setData() {
  let obj = {
    newUseDeptName: {
      label: '新使用部门',
      value: 'newUseDeptName',
      type: 'column',
      show: false,
      hidden: true,
    },
    newManageDeptName: {
      label: '新管理部门',
      value: 'newManageDeptName',
      type: 'column',
      show: false,
      hidden: true,
    },
    newFinanceDeptName: {
      label: '新财务部门',
      value: 'newFinanceDeptName',
      type: 'column',
      show: false,
      hidden: true,
    },
    newLocation: {
      label: '新存放地点',
      value: 'newLocation',
      type: 'column',
      show: false,
      hidden: true,
    },
    reason: {
      label: '原因',
      value: 'reason',
      type: 'column',
      show: false,
      hidden: true,
    },
    newUseUserName: {
      label: '使用人',
      value: 'newUseUserName',
      asValue: 'newUseUser',
      type: 'column',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function showAssetDetail(row) {
  assetDetailInfo.value.id = row.assetId
  assetDetailInfo.value.visible = true
}
//提交
function submit() {
  let data = {
    flowTaskCommentDto: { approvalType: 'submit' },
    processDefinitionKey: 'assetTransfer',
    orderId: infoList.value.data.id,
  }
  submitAssetTransfer(data).then((resp) => {
    if (resp && resp.success) {
      if (resp.msgType === 'messageBox') {
        refreshAssetTransfer(infoList.value.data.id).then()
      }
      refreshDetail()
    }
  })
}
// 按钮审批原因弹窗
function btnFlow(code) {
  const row = infoList.value.data
  const currentBtnFlow = {
    title: '',
    api: null,
  }
  if (code === 'approve') {
    currentBtnFlow.api = checkAssetTransfer
    const data = {
      orderId: row.id,
    }
    currentBtnFlow.api(data).then((resp) => {
      if (resp && resp.success) {
        refreshDetail()
      }
    })
    return
  } else if (code === 'reject') {
    currentBtnFlow.title = '驳回'
    currentBtnFlow.api = rejectAssetTransfer
  } else if (code === 'refuse') {
    currentBtnFlow.title = '拒绝'
    currentBtnFlow.api = refuseAssetTransfer
  }
  proxy
    .$prompt('请输入' + currentBtnFlow.title + '理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: currentBtnFlow.title + '理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderId: row.id,
        checkOpt: value,
      }
      currentBtnFlow.api(data).then((resp) => {
        if (resp && resp.success) {
          refreshDetail()
        }
      })
    })
}
//撤回
function recall() {
  revokeAssetTransfer([infoList.value.data.id]).then((resp) => {
    if (resp && resp.success) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      refreshDetail()
    }
  })
}
//销审
function salesReview() {
  salesReviewTransfer([infoList.value.data.id]).then((resp) => {
    if (resp && resp.success) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      refreshDetail()
    }
  })
}
function update() {
  modifyInfo.value.orderId = infoList.value.data.id
  modifyInfo.value.title = '修改'
  modifyInfo.value.visible = true
}
function returnBack() {
  emits('returnBack', false)
}
function refreshDetail() {
  getMain()
}
function getMain() {
  getAssetTransfer(props.id || props.tableRow.id).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
    }
  })
}
function getList() {
  getAssetTransferDetailCustomizeListAll(filterInfo.value.query).then(
    (resp) => {
      if (resp && resp.success) {
        tableInfo.value.data = resp.data
      }
    }
  )
}

//导出excel
async function exportExcel() {
  excelAssetTransferOrder(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}

const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'assetTransferDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            applicationId: infoList.value.data.id,
            orderId: infoList.value.data.id,
            orderNo: infoList.value.data.orderNo,
          },
          callback: printCallback,
          data: {},
        })
      }
    }
  })
}
function printCallback() {}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      applicationId: infoList.value.data.id,
      orderId: infoList.value.data.id,
      orderNo: infoList.value.data.orderNo,
    },
    callback: printCallback,
    data: {},
  })
  popoverVisible.value = false
}
function getCustomize() {
  let param = {
    tableKey:
      'assetTransferDetail-com.slip.spd.entity.vo.asset.AssetTransferDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = obj.fieldList
      getMain()
      getList()
    }
  })
}
</script>

<style scoped></style>
